const query = require("../db/mysql")
const { success, error } = require("../modle/modle")
class Cartconunt {
    //获取购物车列表
    CartList = async (ctx) => {
        const { user_id } = ctx.query;
        const sql = `select * from carts where user_id="${user_id}"`
        const data = await query(sql)
        //data 数组
        //循环里怎么放异步
        const allP = data.map(item => {
            return query(`select * from shops where id="${item.shop_id}"`)
        })
        const shops = await Promise.all(allP);
        //  console.log(shops,"shops");
        const newData = data.map((item, index) => {
            return { ...shops[index][0], ...item }
        })
        ctx.body = success(newData)
    }
    addList = async (ctx) => {
        const { user_id, shop_id } = ctx.request.body
        //判断商品第一次添加
        const isHaveSql = `select * from carts where user_id="${user_id}" and  shop_id="${shop_id}"`
        const isHave = await query(isHaveSql)
        let sql = ``
        if (isHave.length) {
            //如果不是第一次，则执行count++
            const nowData = isHave[0]
            sql = `update shops set count="${nowData.count += 1}" where id="${nowData.id}"`
        } else {
            //如果是第一次，则指向添加操作，count默认为
            sql = `insert into carts (user_id,shop_id,count) values ("${user_id}","${shop_id}",1)`
        }
        const data = await query(sql)
        if (data.affectedRows === 1) {
            ctx.body = success("添加成功")
        } else {
            ctx.body = error("添加失败")
        }
    }

    delList = async (ctx) => {
        const { id } = ctx.params;
        const sql = `delete from carts where id="${id}" `
        const data = await query(sql)
        if (data.affectedRows === 1) {
            ctx.body = success("删除成功")
        } else {
            ctx.body = error("删除失败")
        }
    }
    bianList=async (ctx)=>{
        const {id,count}=ctx.request.body
        const sql=`update carts set count="${count}" where id="${id}"`
        const data=await query(sql);
        console.log(data);
        
        if(data.affectedRows===1){
            ctx.body=success("编辑成功")
        }else{
            ctx.body=error("编辑失败")
        }
    }
}
module.exports = new Cartconunt()